package com.xuecheng.system.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.domain.User;
import com.xuecheng.system.mappers.UserMapper;
import com.xuecheng.system.service.UserService;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.验证请求参数是否为空
        String phone = dto.getUsername();
        String password = dto.getPassword();
        String utype = dto.getUtype();
        //2.根据手机号和用户类型从数据库查询
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        wrapper.eq(User::getUtype,utype);
        User user = userMapper.selectOne(wrapper);
        //2-1 验证用户名是否存在，不存在，返回错误信息：用户名不存在
        if (user == null) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        //2-2 存在：获取密码,将输入的密码加密
        String dbPassword = user.getPassword();
        String md5Password = DigestUtil.md5Hex(password);
        //3.两者比较,不同:返回密码错误
        if (!dbPassword.equals(md5Password)) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        //4.密码相同，生成token
        Map<String, Object> map = new HashMap<>();
        map.put("userId",user.getId());
        map.put("companyId",user.getCompanyId());
        map.put("companyName",user.getCompanyName());
        String token = JwtUtils.createToken(map, 240);
        //5.构造返回参数
        LoginVo loginVo = new LoginVo();
        loginVo.setAccess_token(token);
        loginVo.setUsername(user.getName());
        return ResponseResult.okResult(loginVo);
    }
}
